package com.telit.communicate.communicate;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;


/**
 * @author zhouyu
 * @description netty启动器
 **/
@Component
@Slf4j
public class NettyServerStarter {
    private ExecutorService executorService;

    @Autowired
    private NettyServer nettyServer;


    /**
     * 创建线程池来单独开启netty
     */
    @PostConstruct
    public void setup() {
        ThreadFactory namedThreadFactory = new ThreadFactoryBuilder()
                .setNameFormat("NettyStarter-Thread-%d").build();
        executorService = Executors.newSingleThreadExecutor(namedThreadFactory);
        runWebSocketServer();
        //创建消息实例缓存
        MsgInstanceCache.createInstanceCache();
    }


    private void runWebSocketServer() {
        executorService.execute(() -> {
            try {
                log.info("netty server starting ...");
                //开启服务端
                nettyServer.startServer();
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    @PreDestroy
    public void cleanup() {
        executorService.shutdown();
    }
}
